'use client';

import { Button } from '@/components/ui/button';
import { Bell, BellOff } from 'lucide-react';
import { useEventNotifications } from '@/hooks/useEventNotifications';
import { useState, useEffect } from 'react';

export const EventNotificationButton = () => {
  const [mounted, setMounted] = useState(false);
  const [notificationsEnabled, setNotificationsEnabled] = useState(false);
  
  const { 
    newEventsCount, 
    isPolling, 
    clearNewEventsCount, 
    togglePolling 
  } = useEventNotifications(notificationsEnabled);

  useEffect(() => {
    setMounted(true);
    // 從 localStorage 恢復通知設定
    const saved = localStorage.getItem('eventNotificationsEnabled');
    if (saved !== null) {
      setNotificationsEnabled(JSON.parse(saved));
    }
  }, []);

  const handleToggleNotifications = () => {
    const newState = !notificationsEnabled;
    setNotificationsEnabled(newState);
    localStorage.setItem('eventNotificationsEnabled', JSON.stringify(newState));
    togglePolling();
    
    if (newState) {
      // 清除現有的新事件計數
      clearNewEventsCount();
    }
  };

  // 防止 hydration 錯誤
  if (!mounted) {
    return (
      <Button variant="outline" size="sm" disabled>
        <Bell className="w-4 h-4" />
      </Button>
    );
  }

  return (
    <Button
      variant={notificationsEnabled ? "primary" : "outline"}
      size="sm"
      onClick={handleToggleNotifications}
      className="relative"
      title={notificationsEnabled ? "關閉事件通知" : "開啟事件通知"}
    >
      {notificationsEnabled ? (
        <Bell className="w-4 h-4" />
      ) : (
        <BellOff className="w-4 h-4" />
      )}
      
      {/* 新事件計數徽章 */}
      {notificationsEnabled && newEventsCount > 0 && (
        <span className="absolute -top-2 -right-2 bg-red-500 text-white text-xs rounded-full w-5 h-5 flex items-center justify-center font-bold">
          {newEventsCount > 99 ? '99+' : newEventsCount}
        </span>
      )}
      
      <span className="ml-2 hidden sm:inline">
        {notificationsEnabled ? '通知開啟' : '通知關閉'}
      </span>
    </Button>
  );
};